<template>
  <div>
    <!-- loading加载表格时间 -->
    <el-table
      @selection-change="handleSelectionChange"
      v-loading="tableLoading"
      element-loading-text="少女祈祷中。。。"
      height="700"
      :data="
        tableData.filter(
          (data) =>
            !search ||
            data.title.toLowerCase().includes(search.toLowerCase()) ||
            data.content.toLowerCase().includes(search.toLowerCase())
        )
      "
    >
      <!-- 表头多选模式 -->
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="_id" label="唯一ID" width="240px" />

      <el-table-column prop="comment" label="来自评论" min-width="80px" />
      <el-table-column prop="youSay" label="回复" min-width="80px" />

      <el-table-column prop="createdAt" label="时间" min-width="80px">
        <template v-slot="scope">
          <span>{{ scope.row.createdAt | fullDateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="user" label="昵称" min-width="80px">
        <template v-slot="scope">
          <span>{{ scope.row.user.nick }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="消息内容" min-width="80px" />
      <el-table-column align="right">
        <!-- v-slot自定义头部子组件 -->
        <template #header>
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入标题或内容搜索"
          />
        </template>
      </el-table-column>
      <!-- 右侧固定删除编辑列 -->
      <el-table-column fixed="right" align="center" width="200px">
        <template #header>
          <el-button
            size="small"
            type="primary"
            native-type="submit"
            @click="
              dialogFormVisible = true
              //初始化model
              model = {}
            "
          >
            <span>新建消息</span>
          </el-button>
          <el-button size="small" type="danger" @click="remove()">
            <span>批量删除</span>
          </el-button>
        </template>
        <!-- v-slot传入默认组件 命名为scope -->
        <template v-slot="scope">
          <el-button
            size="mini"
            @click="
              edit(scope.row)
              dialogFormVisible = true
            "
          >
            <span>编辑</span>
          </el-button>
          <!-- 单删除确认气泡 -->
          <el-popconfirm
            @confirm="singleRemove(scope.row)"
            confirmButtonText="肯定"
            cancelButtonText="不了"
            icon="el-icon-info"
            iconColor="red"
            :title="confirmTitle"
          >
            <el-button
              @click="changeTitle(scope.row)"
              slot="reference"
              size="mini"
              type="danger"
            >
              <span>删除</span>
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改弹窗 -->
    <el-dialog
      @close="fetch"
      center
      title="填写消息"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="model"
        :rules="rules"
        ref="ruleForm"
        @submit.native.prevent
      >
        <!-- prop 接受子组件 name值  validate-event绑定提交时验证-->
        <el-form-item prop="comment" label="评论唯一ID">
          <el-input :validate-event="false" v-model="model.comment"> </el-input>
        </el-form-item>
        <el-form-item prop="content" label="回复内容">
          <el-input
            type="textarea"
            :validate-event="false"
            placeholder="输入消息内容"
            v-model="model.content"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="you" label="you 唯一ID">
          <el-input
            :validate-event="false"
            placeholder="输入消息you"
            v-model="model.you"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="user" label="user 唯一ID">
          <el-input
            :validate-event="false"
            placeholder="输入 user "
            v-model="model.user"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="youSay" label="输入youSay">
          <el-input
            :validate-event="false"
            placeholder="输入消息you"
            v-model="model.youSay"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          <span>取消</span>
        </el-button>
        <!-- 提交时传入表单 -->
        <el-button
          type="primary"
          native-type="submit"
          @click="save('ruleForm')"
        >
          <span>确定</span>
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 删除确认文本
      confirmTitle: ``,
      // 多选变量
      multipleSelection: [],
      //默认加载loading
      tableLoading: true,
      model: {},
      rules: {
        // 表单验证规则
      },
      tableData: [],
      search: "",
      //默认隐藏弹窗
      dialogFormVisible: false,
    }
  },
  methods: {
    // 气泡弹窗删除确认
    changeTitle(row) {
      this.confirmTitle = `确定删除消息吗？`
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    //保存与修改
    save(formName) {
      // validate 验证表单返回值
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res
          //判断新增或修改
          if (!this.model._id) {
            //发送数据库新增post请求
            res = await this.$http.post("rest/messages", this.model)
          } else {
            res = await this.$http.put("rest/messages", this.model)
          }
          // 判断是否已存在
          if (res.data.name != "MongoError") {
            //修改成功关闭弹窗
            this.dialogFormVisible = false
            //重新拉取数据
            this.fetch()
            //创建消息提醒
            this.$notify({
              title: "成功",
              position: "top-left",
              type: "success",
              message: "消息操作成功！",
            })
          } else {
            this.fetch()
            this.$notify({
              title: "警告",
              position: "top-left",
              type: "warning",
              message: "消息已存在！",
            })
          }
        }
      })
    },
    //编辑弹窗传入对应行数据
    edit(row) {
      this.model = row
    },
    //多行删除对应数据
    async remove() {
      let params = []
      this.multipleSelection.forEach((item) => params.push(item))

      if (params.length == 0) {
        return this.$message({
          type: "warning",
          message: "请选择数据！",
        })
      } else {
        await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        const res = await this.$http.delete(`rest/messages`, { data: params })
        this.fetch()
        this.$notify({
          title: "成功",
          position: "top-left",
          type: "success",
          message: "消息已删除！",
        })
      }
    },
    //单个删除
    async singleRemove(row) {
      const res = await this.$http.delete(`rest/messages/${row._id}`)

      this.fetch()
      this.$notify({
        title: "成功",
        position: "top-left",
        type: "success",
        message: "消息已删除！",
      })
    },
    //获取数据
    async fetch() {
      const res = await this.$http.get("rest/messages")
      this.tableData = res.data
      console.log(res.data)
    },
  },
  created() {
    //页面创建完自动加载数据
    this.fetch()
    //loading时间
    setTimeout(() => {
      this.tableLoading = false
    }, 1500)
  },
}
</script>
